/**
 * $Id$
 *
 * Copyright (c) 2014 ChinaSoft International, Ltd. All rights reserved
 * JointForce Project
 *
 */
package com.csi.jf.crucible.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.csi.jf.crucible.common.config.JfConstants;
import com.csi.jf.crucible.ptservice.controller.CodePackagesController;
import com.csi.jf.crucible.ptservice.model.CodePackages;

/**
 * @Title: PackageUtils.java
 * @Description: <br>
 *               <br>
 * @Company: Chinasofti
 * @Created on 2014-7-2 下午2:57:11
 * @author zhangmh
 * @version $Revision: 1.0 $
 * @since 1.0
 */
public class PackageUtils {
    
    protected static final Logger LOG = LoggerFactory.getLogger(PackageUtils.class);

    public static String createPakcageName(CodePackages codePackages){
        //initialize package directory
        File dir = new File(JfConstants.PTS_PACKAGE_HOME);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String filename = codePackages.getPackagename()+codePackages.getExtendName();
        return dir.getAbsoluteFile()+File.separator+codePackages.getProjectId()+"-"+filename+"-"+codePackages.getPackageversion()+".zip";
    }
    
    public static void uploadPackage(CodePackages codePackages,File packageFile)throws Exception{
        FileOutputStream fos = null;
        FileInputStream input = null;
        try {
            File descFile = new File(PackageUtils.createPakcageName(codePackages));
            if(descFile.exists()){
                descFile.delete();
            }else{
                descFile.createNewFile();
            }
            fos = new FileOutputStream(descFile);
            input = new FileInputStream(packageFile);
            
            codePackages.setPackagesize(Long.valueOf(input.available()));
            
            byte[] data = new byte[1024 * 4];
            int len = -1;
            while ((len = input.read(data)) != -1) {
                fos.write(data, 0, len);
                fos.flush();
            }
            fos.close();
        } catch (Exception e) {
            LOG.error(e.getMessage(),e);
        } finally{
            if(fos!=null){
                try {
                    fos.close();
                } catch (Exception e) {
                    LOG.error(e.getMessage(),e);
                }
            }
        }
    }

}
